/**
 *管理对象的闪烁  
 */
package utils.effects
{
	import flash.display.DisplayObject;
	import flash.events.TimerEvent;
	import flash.filters.GlowFilter;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	
	import org.osmf.events.TimeEvent;

	public class Flicker
	{
		private static var _instance:Flicker;
		private var _flickerMap:Dictionary;
		private var _glowFilterMap:Dictionary;
		
		public function Flicker()
		{
		}
		
		private static function get instance():Flicker
		{
			if(_instance == null)
			{
				_instance = new Flicker();
				_instance._flickerMap = new Dictionary();
				_instance._glowFilterMap = new Dictionary();
			}
				
			return _instance;
		}
		
		/**
		 *为显示对象添加闪烁 效果 
		 * @param obj
		 * @param $lightColor
		 * @param $delay
		 * @param $time：闪烁的次数，0表示一直闪烁
		 * 
		 */						
		public static function addFlicker(obj:DisplayObject, $lightColor:uint, $delay:uint=1000, $repeatCount:uint=0):void
		{
			if(instance._flickerMap[obj])//同一个显示对象以前的闪烁效果将被最新的代替
			{
				Flicker.removeFlicker(obj);
			}
			var timer:Timer = new Timer($delay,$repeatCount);
			timer.addEventListener(TimerEvent.TIMER,onTimer,false,0,true);
			timer.start();
			instance._flickerMap[obj] = {color:$lightColor, flickerTimer:timer};
			if(!obj.filters)
				obj.filters = [instance.getFilter($lightColor)];
			else
				obj.filters.push(instance.getFilter($lightColor));
			
			function  onTimer(evt:TimeEvent):void
			{
				if(!obj.filters)
					obj.filters = [instance.getFilter($lightColor)];
				else
				{
					var index:int = obj.filters.indexOf(instance.getFilter($lightColor));
					if(index == -1)
						obj.filters.push(instance.getFilter($lightColor));
					else
						obj.filters.splice(index,1);
				}
					
			}
		}
		
		
		
		/**
		 *移除 obj上用addFlicker方法添加的闪烁效果
		 * @param obj
		 * 
		 */		
		public static function removeFlicker(obj:DisplayObject):void
		{
			var flickerData:Object = instance._flickerMap[obj];
			if(flickerData == null)
				return;
			var index:int;
			index = obj.filters.indexOf(instance.getFilter(flickerData.color));
			if(index != -1)
				obj.filters.splice(index,1);
			(flickerData.flickerTimer as Timer).stop();
			flickerData.flickerTimer = null;
			flickerData = null;
			delete instance._flickerMap[obj];
		}
		
		private function getFilter($color:uint):GlowFilter
		{
			if(_glowFilterMap[$color] == null)
			{
				_glowFilterMap[$color] = new GlowFilter($color);
			}
			return _glowFilterMap[$color] as GlowFilter;
		}
	}
}